﻿// 资源加载管理器      
// 功能： 本功能是在Unity的Resources类的基础之上，增加了“缓存”的处理。

using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using MotionFramework.Resource;

namespace MotionFramework.UIKit
{
    public class ResourcesMgr : MonoBehaviour
    {
        /* 字段 */
        private static ResourcesMgr m_Instance;              //本脚本私有单例实例
        private Hashtable m_HashSet = null;                        //容器键值对集合


        /// <summary>
        /// 得到实例(单例)
        /// </summary>
        /// <returns></returns>
        public static ResourcesMgr GetInstance()
        {
            if (m_Instance == null)
            {
                m_Instance = new GameObject("_ResourceMgr").AddComponent<ResourcesMgr>();
                DontDestroyOnLoad(m_Instance);
            }
            return m_Instance;
        }

        void Awake()
        {
            m_HashSet = new Hashtable();
        }

        /// <summary>
        /// 调用资源（带对象缓冲技术）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="isCatch"></param>
        /// <returns></returns>
        public T LoadResource<T>(string path, bool isCatch) where T : UnityEngine.Object
        {
            if (m_HashSet.Contains(path))
            {
                return m_HashSet[path] as T;
            }

            var asset = ResourceManager.Instance.LoadAssetSync<T>(path);
            T TResource = asset.AssetObject as T;
            //T TResource = Resources.Load<T>(path);
            if (TResource == null)
            {
                Debug.LogError(GetType() + "/GetInstance()/TResource 提取的资源找不到，请检查。 path=" + path);
            }
            else if (isCatch)
            {
                m_HashSet.Add(path, TResource);
            }

            return TResource;
        }

        /// <summary>
        /// 调用资源（带对象缓冲技术）
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isCatch"></param>
        /// <returns></returns>
        public GameObject LoadAsset(string path, bool isCatch)
        {
            var resource = LoadResource<GameObject>(path, isCatch);
            if (resource == null)
            {
                Debug.LogError(GetType() + "/LoadAsset()/克隆资源不成功，请检查。 path=" + path);
                return resource;
            }

            return GameObject.Instantiate<GameObject>(resource);
        }       
    }//Class_end
}